﻿using KAKA.Domain;
using Morus;
using System;
using System.Collections.Generic;
using System.Linq;

namespace KAKA.Repository
{
    public class CachingDictionaryRepository : DecoratedDictionaryRepository
    {
        private int CacheDurationInMinutes { get; set; }

        public CachingDictionaryRepository(IDictionaryRepository innerRepository, int cacheDurationInMinutes)
            : base(innerRepository)
        {
            CacheDurationInMinutes = cacheDurationInMinutes;
        }

        public override IEnumerable<Dictionary> FindByType(string type)
        {
            string CacheKey = "dictionary:{0}".FormatWith(type);

            IEnumerable<Dictionary> result;

            Cache.TryGet(CacheKey, out result);

            if (result == null)
            {
                result = base.FindByType(type);

                if ((result != null) && (!Cache.Contains(CacheKey)))
                {
                    Cache.Set(CacheKey, result, DateTime.Now.AddMinutes(CacheDurationInMinutes));
                }
            }

            return result;
        }
    }
}
